<template>
  <div>
    <el-card style="width: 100%; max-width: 650px">
      <el-form :rules="rules" ref="updateRef" @submit.native.prevent :model="loginUser" label-width="80px"
               style="width: 100%">
        <div style="text-align: center; margin-bottom: 20px;">
          <el-upload
              class="avatar-uploader"
              :action="uploadURL"
              :headers="{token:loginUser.token}"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleError"
              :before-upload="beforeUpload">
            <i v-if="!loginUser.avatar" class="el-icon-plus avatar-uploader-icon el-upload"></i>
            <el-image v-if="loginUser.avatar" :src="loginUser.avatar" class="avatar"></el-image>
          </el-upload>
        </div>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginUser.userName" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-input v-model="loginUser.role" placeholder="" readonly></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="loginUser.name" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="loginUser.phone" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="相片" prop="photo" v-if="loginUser.role==='安全检查员'">
          <el-upload
              class="photo-uploader"
              :action="uploadURL"
              :headers="{token:loginUser.token}"
              :show-file-list="false"
              :on-success="handlePhotoSuccess"
              :before-upload="beforeUpload">
            <i v-if="!loginUser.photo" class="el-icon-plus photo-uploader-icon el-upload"></i>
            <el-image v-if="loginUser.photo" :src="loginUser.photo" fit="cover" class="photo"></el-image>
          </el-upload>
        </el-form-item>
        <el-form-item label="负责楼栋" prop="buildingId" v-if="loginUser.role==='安全检查员'">
          <el-select clearable filterable v-model="loginUser.buildingId" placeholder="请选择楼栋">
            <el-option v-for="item in buildings" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房产" prop="selectedHouse" v-if="loginUser.role==='业主'">
            <el-cascader filterable :options="houseTree"
                         v-model="loginUser.houseCoordinate" placeholder="请选择房产"></el-cascader>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email" v-if="loginUser.role==='业主'">
          <el-input v-model="loginUser.email" placeholder=""></el-input>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="primary" native-type="submit" @click="update">保 存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {defineComponent} from 'vue'
import request from "@/utils/request";

export default defineComponent({
  name: "PersonView",
  data() {
    return {
      uploadURL: request.defaults.baseURL + '/user/file/upload',
      // loginUser: JSON.parse(localStorage.getItem('user')) || {},
      loginUser: {},
      houseTree: [],
      buildings: [],
      rules: {
        // phone: [{validator: this.validatePhone, trigger: 'blur'}]
      },
      photoFile: [],
    }
  },
  mounted() {
    this.getPersonalInfo()
  },
  methods: {
    //获取个人信息
    getPersonalInfo(){
      this.$request.get("/user/user/getPersonalInfo").then(res => {
        if (res.code === 200) {
          this.loginUser = res.data
          localStorage.setItem('user', JSON.stringify(this.loginUser))
        } else {
          this.$message.error(res.msg)
        }
      })
      this.getHouseTree()
      this.getBuildings()
    },
    //获取房屋的树形结构
    getHouseTree() {
      this.$request.get('/house/house/getHouseTree').then(res => {
        if (res.code === 200) {
          this.houseTree = res.data
        } else {
          this.$message.error('获取房屋信息失败')
        }
      })
    },
    // 获取所有楼栋
    getBuildings() {
      this.$request.get('/house/building/getBuildings').then(res => {
        if (res.code === 200) {
          this.buildings = res.data
        } else {
          this.$message.error('获取楼栋信息失败')
        }
      })
    },
    validatePhone(rule, value, callback) {
      //中国大陆手机号码校验正则表达式
      const regex = /^1[3-9]\d{9}$/;
      if (value && !regex.test(value)) {
        callback(new Error('电话号码格式不正确'))
      } else {
        callback()
      }
    },
    //保存个人信息
    update() {
      // //先上传图片
      // console.log('上传的数据，', data)
      // let formData = new FormData()
      // formData.append('file', data)
      // request.postForm('/user/file/upload', formData).then(res => {
      //   if (res.code === 200) this.loginUser.avatar = res.data
      //   else this.$message.error(res.msg)
      // })
      // //保存到数据库
      this.$refs['updateRef'].validate(valid => {
        if (valid) {
          request.put('/user/user/updatePersonalInfo', this.loginUser).then(res => {
            if (res.code === 200) {
              //更新本地存储
              localStorage.setItem('user', JSON.stringify(this.loginUser))
              //将消息传递给父组件
              this.$emit('update:user')//,this.loginUser
              this.$message.success('保存成功')
            } else{
              this.$message.error(res.msg)
            }
          })
        }
      })

    },
    //头像上传成功后操作
    handleAvatarSuccess(res) {
      if (res.code === 200){
        this.loginUser.avatar = res.data
      } else if (res.code === 401) {
        this.$message.error(res.msg)
        this.$router.push('/login')
      } else {
        this.$message.error(res.msg)
      }
    },
    //照片上传成功后操作
    handlePhotoSuccess(res) {
      if (res.code === 200){
        this.loginUser.photo = res.data
      } else if (res.code === 401) {
        this.$message.error(res.msg)
        this.$router.push('/login')
      } else {
        this.$message.error(res.msg)
      }
    },
    //上传失败
    handleError(){
      this.$message.error('上传失败')
    },
    beforeUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
  }
})
</script>

<style scoped>
.avatar-uploader .el-upload {
  border-radius: 50%;
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}

.photo-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.photo-uploader .el-upload:hover {
  border-color: #409EFF;
}

.photo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 133.5px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.photo {
  width: 133.5px;
  height: 178px;
  display: block;
}
</style>
